<?php
/**
 * 前台control父类,商城control父类,会员control父类
 *
 * * @网店运维 (c) 2015-2018 ShopWWI Inc. (http://www.shopwwi.com)
 * @license    http://www.shopwwi.c om
 * @link       交流群号：111731672
 * @since      网店运维提供技术支持 授权请购买shopnc授权
 */



defined('ByShopWWI') or exit('Access Invalid!');

/********************************** 前台control父类 **********************************************/
class MobileControl{

    //客户端类型
    protected $client_type_array = array('android', 'wap', 'wechat', 'ios', 'windows');

    public function __construct(){
        /*if(empty($_SESSION['store_id'])){
            $store_info = Model('store')->getStoreInfo(array('store_name'=>'金福银贵'));
            if(!empty($store_info['store_id'])){
                $_SESSION['store_id'] = $store_info['store_id'];
            }
        }*/
        $this -> setCartNumOp();
    }

    public function setCartNumOp() {
        $model_cart = Model('cart');
        if ($_SESSION['member_id']){
            //登录后
            $cart_list  = $model_cart->getCartNum('db',array('buyer_id'=>$_SESSION['member_id']));
            Tpl::output("cart_num_con", $model_cart->cart_goods_num);
        }
    }

    public function autoLoginOp(){
        $atn = $_POST['atn'];
        $atp = $_POST['atp'];
        if( $_SESSION['is_login'] != 1 &&  !empty($atn) && !empty($atp) ){
            $model_member = new memberModel();
            $user_name = $atn;
            $sql = "SELECT * FROM #__member WHERE member_name = '$user_name' OR member_mobile = '$user_name' OR member_email = '$user_name'";
            $member_info = Db::queryRow($sql);
            if(is_array($member_info) and !empty($member_info)) {
                if(!decryptionAlgorithm($atp,$member_info['member_passwd'])){
                    return;
                }
                if(!$member_info['member_state']){
                    return;
                }
                /**
                 * 登录时间更新
                 */
                $update_info	= array(
                    'member_login_num'=>($member_info['member_login_num']+1),
                    'member_login_time'=>time(),
                    'member_old_login_time'=>$member_info['member_login_time'],
                    'member_login_ip'=>getIp(),
                    'member_old_login_ip'=>$member_info['member_login_ip']);
                $model_member->updateMember($update_info,$member_info['member_id']);
                /**
                 * 写入session
                 */
                $seller_info = Model('seller')->getSellerInfo(array('seller_name' => $user_name));
                $_SESSION['is_seller']='';
                if($seller_info) {
                    $_SESSION['store_id'] = intval($seller_info['store_id']);
                    $_SESSION['is_seller']	= 1;
                }

                $_SESSION['is_login']	= '1';
                $_SESSION['member_id']	= $member_info['member_id'];
                $_SESSION['member_name']= $member_info['member_name'];
                $_SESSION['member_email']= $member_info['member_email'];
                $_SESSION['member_mobile']= $member_info['member_mobile'];
                $_SESSION['is_buy'] = $member_info['is_buy'];

                if ($GLOBALS['setting_config']['qq_isuse'] == 1 && trim($member_info['member_qqopenid'])){
                    $_SESSION['openid']		= $member_info['member_qqopenid'];
                }
                if ($GLOBALS['setting_config']['sina_isuse'] == 1 && trim($member_info['member_sinaopenid'])){
                    $_SESSION['slast_key']['uid'] = $member_info['member_sinaopenid'];
                }

                // cookie中的cart存入数据库
                $this->mergecart();

                //添加会员积分
                if (C('points_isuse')){
                    //一天内只有第一次登录赠送积分
                    if(trim(@date('Y-m-d',$member_info['member_login_time']))!=trim(date('Y-m-d'))){
                        $points_model =new pointsModel();
                        $points_model->savePointsLog('login',array('pl_memberid'=>$member_info['member_id'],'pl_membername'=>$member_info['member_name']),true);
                    }
                }
            }
        }
    }

    public function isLogin(){
        if(!isset($_SESSION['is_login']) || $_SESSION['is_login'] != 1){
            appMessage('请先登录','index.php?act=login');
        }
    }

    //商城信息
    protected function getStoreInfo($store_id){
        $model_store	=new storeModel();
        $store_info = array();
        if(intval($store_id) > 0) {
            $store_info	= $model_store->shopStore(array('store_id'=>$store_id));
        } else {
            appMessage('该商城已关闭');
        }
        if($store_info['store_state'] == '0' || (intval($store_info['store_end_time']) != 0 && $store_info['store_end_time'] <= time())){
            appMessage('该商城已关闭');
        }
        $store_info = $model_store->getStoreInfoDetail($store_info);
        Tpl::output('store_info',$store_info);
        Tpl::output('hot_sales',$store_info['hot_sales']);
        Tpl::output('hot_collect',$store_info['hot_collect']);
        Tpl::output('goods_class_list',$store_info['goods_class_list']);
        Tpl::output('page_title',$store_info['store_name']);
        if($store_info['store_theme'] == 'style8'){
            $theme_model =new store_themeModel();
            $condition = array();
            $condition['style_id'] = $store_info['store_theme'];
            $condition['store_id'] = $store_id;
            $theme_list = $theme_model->getList($condition);
            Tpl::output('theme',$theme_list[0]);
        }
        return $store_info;
    }

    //商品评论统计
    protected function getCommentCount($goods_id,$store_id){
        $where = '';
        $where .= " AND geval_goodsid = $goods_id";
        $where .= " AND geval_storeid = $store_id";
        $where .= " AND geval_type = 1";
        $where .= " AND geval_state = 0";
        $where .= ' AND geval_showtime <= '.time();
        $sql = "SELECT geval_scores FROM #__evaluate_goods WHERE 1 $where";
        $res = Db::queryAll($sql);
        $arr = array();
        $arr['scoreCount1']=0;
        $arr['scoreCount2']=0;
        $arr['scoreCount3']=0;
        foreach($res as $k=>$v){
            switch ($v['geval_scores']){
                case 1:
                    $arr['scoreCount1']++;
                    break;
                case 0:
                    $arr['scoreCount2']++;
                    break;
                case -1:
                    $arr['scoreCount3']++;
                    break;
            }
        }
        return $arr;
    }

    /**
     * 统计留言未读条数
     *
     * @return int
     */
    protected function receivedCommonNewNum()
    {
        $model_message = new messageModel();
        $countnum = $model_message->countMessage(array('message_type' => '2', 'to_member_id_common' => $_SESSION['member_id'], 'no_message_state' => '2', 'message_open_common' => '0'));
        return $countnum;
    }

    /**
     * 统计系统消息未读条数
     *
     * @return int
     */
    protected function receivedSystemNewNum()
    {
        $message_model = new messageModel();
        $condition_arr = array();
        $condition_arr['message_type'] = '1'; //系统消息
        $condition_arr['to_member_id'] = $_SESSION['member_id'];
        $condition_arr['no_del_member_id'] = $_SESSION['member_id'];
        $condition_arr['no_read_member_id'] = $_SESSION['member_id'];
        $countnum = $message_model->countMessage($condition_arr);
        return $countnum;
    }

    /**
     * 统计私信未读条数
     *
     * @return int
     */
    protected function receivedPersonalNewNum()
    {
        $model_message = new messageModel();
        $countnum = $model_message->countMessage(array('message_type' => '0', 'to_member_id_common' => $_SESSION['member_id'], 'no_message_state' => '2', 'message_open_common' => '0'));
        return $countnum;
    }

    protected function _assignMobileData($page){
        $pageInfo = MobilePage::getPage($page->getEachNum());
        $pageInfo['item_count'] = $page->getTotalNum();
        MobilePage::formatPage($pageInfo);
        Tpl::output('pageInfo', $pageInfo);
    }

    /**
     * cookie中的cart存入数据库
     *
     */
    protected function mergecart(){
        //登录之后,判断是否存在进货车cookie
        if (cookie('cart') && $_SESSION['member_id']){
            //读取cookie进货车信息
            $cart_str = cookie('cart');
            if (get_magic_quotes_gpc()) $cart_str = stripslashes($cart_str);//去除斜杠
            $cookie_cart = unserialize($cart_str);
            if (!empty($cookie_cart)){
                //取出已有进货车信息
                $model_cart	=new cartModel();
                $cart_goods_arr	= $model_cart->listCart();
                $cart_goodsspecid_arr = array();
                if(!empty($cart_goods_arr)) {
                    foreach ($cart_goods_arr as $v){
                        $cart_goodsspecid_arr[] = $v['spec_id'];
                    }
                }
                //剔除数据库进货车与cookie进货车的重复项
                foreach ($cookie_cart as $k=>$v){
                    if (is_array($cart_goodsspecid_arr) && in_array($k,$cart_goodsspecid_arr)){
                        unset($cookie_cart[$k]);
                    }
                }
                unset($cart_goodsspecid_arr);
                unset($cart_goods_arr);

                //查询cookie进货车商品信息
                if (!empty($cookie_cart)){
                    $cookie_cart_goods=array();
                    foreach($cookie_cart as $spec_id=>$cart_row){
                        $logicGoods=logic_goodsModel::getObject($spec_id);
                        $goodsInfo=$logicGoods->getGoodsInfo();
                        if($goodsInfo['store_id']!==$_SESSION['store_id']){
                            $cookie_cart_goods[$spec_id]=$goodsInfo;
                        }
                    }
                    //查询在cookie进货车中,不是商城自己的商品，未禁售，上架，有库存的商品
                    /*$sql="SELECT goods.goods_id,goods.goods_name,goods.store_id,goods.goods_image,goods.spec_open,goods_spec.* FROM #__goods as goods LEFT JOIN #__goods_spec as goods_spec ON goods.goods_id=goods_spec.goods_id WHERE goods.store_id <> '{$_SESSION['store_id']}' and goods.goods_show= '1' and goods.goods_state= '0' and goods_spec.spec_id in ('".implode("','",array_keys($cookie_cart))."') and goods_spec.spec_goods_storage > 0 order by goods.goods_id desc";
                    $cookie_cart_goods =db::queryAll($sql);*/
                    if (!empty($cookie_cart_goods)){
                        foreach ($cookie_cart_goods as $k=>$v){
                            //cookie进货车信息，插入数据库进货车
                            $insert_cart = array();
                            $insert_cart						= array();
                            $insert_cart['member_id']			= $_SESSION['member_id'];
                            $insert_cart['store_id']			= $v['store_id'];
                            $insert_cart['goods_id']			= $v['goods_id'];
                            $insert_cart['goods_name']			= $v['goods_name'];
                            $insert_cart['spec_id']				= $v['spec_id'];
                            //构造进货车规格信息
                            $insert_cart['spec_info'] = '';
                            if ($v['spec_open'] == 1 && !empty($v['spec_goods_spec']) && !empty($v['spec_name'])){
                                $spec_name = unserialize($v['spec_name']);
                                if (!empty($spec_name)){
                                    $spec_name = array_values($spec_name);
                                    $spec_goods_spec = unserialize($v['spec_goods_spec']);
                                    $i = 0;
                                    foreach ($spec_goods_spec as $k=>$specv){
                                        $insert_cart['spec_info'] .= $spec_name[$i].":".$specv."&nbsp;";
                                        $i++;
                                    }
                                }
                            }
                            $insert_cart['goods_store_cost_price'] = $v['spec_goods_cost_price'];
                            $insert_cart['goods_store_cost_rate'] = $v['spec_goods_cost_rate'];
                            $insert_cart['goods_store_price']	= $v['spec_goods_price'];
                            //商品购买数量，根据库存判断
                            $insert_cart['goods_num']			= intval($cookie_cart[$v['spec_id']]['num']);
                            if ($insert_cart['goods_num'] > $v['spec_goods_storage']){
                                $insert_cart['goods_num'] = $v['spec_goods_storage'];
                            }
                            $insert_cart['goods_images']		= $v['goods_image'];
                            Db::insert('cart',$insert_cart);
                        }
                    }
                }
            }
            setNcCookie('cart','',-3600);
            setNcCookie('goodsnum','',-3600);		// 进货车商品种数
        }

    }
    protected function orderStateInfo($state_code, $refund_state = 0) {
        $lang_string = "";
        $state_code = intval($state_code);
        switch ($state_code) {
            case 0:
                $lang_string = '订单已取消';
                return $lang_string;
            case 10:
                $lang_string = '待买家付款';
                return $lang_string;
            case 11:
                $lang_string = '待卖家收款';
                return $lang_string;
            case 15:
                $lang_string = '货到付款，等待发货';
                return $lang_string;
            case 20:
                $lang_string = '买家已付款，待卖家发货';
                return $lang_string;
            case 30:
                $lang_string = '卖家已发货';
                return $lang_string;
            case 40:
                $lang_string = '交易成功';
                if (!($refund_state == 2)) {
                    break;
                }
                $lang_string = '交易关闭';
                return $lang_string;
            case 50:
                $lang_string = '已提交，待确认';
                return $lang_string;
            case 60:
                $lang_string = '已确认，待发货';
                return $lang_string;
                $lang_string = '交易成功';
        }
        return $lang_string;
    }

    /**
     * 获得订单状态描述
     */
    protected function pointorder_state($order_step) {
        $lang_string = "";
        $state_code = intval($order_step);
        switch ($state_code) {
            case 10 :
                $lang_string = '未付款';
                return $lang_string;
                break;
            case 11 :
                $lang_string = '已付款，待确认收款';
                return $lang_string;
                break;
            case 2 :
                $lang_string = '订单已取消';
                return $lang_string;
                break;
            case 20 :
                $lang_string = '待发货';
                return $lang_string;
                break;
            case 30 :
                $lang_string = '已发货，待收货';
                return $lang_string;
                break;
            case 40 :
                $lang_string = '订单已完成';
                return $lang_string;
                break;
        }
        return $lang_string;
    }
    /*
     * 订单列表
     * */
    protected function orderlist(){
        $model_order =new orderModel();
        $page	= new Page();
        $page->setEachNum(10);
        $page->setStyle('admin');
        /**
         * 实例化买家订单模型
         */
        $model_my_order =new my_orderModel();
        /*搜索条件*/
        $array	= array();
        $array['order_sn']		= trim($_GET['order_sn']);
        $array['order_state']	= (in_array(trim($_GET['state_type']),array('order_pay','order_submit','order_pay_confirm','order_no_shipping','order_shipping','order_finish','order_cancal','order_refer','order_confirm')) ? trim($_GET['state_type']) : '');
        if($_GET['state_type'] == 'noeval'){
            $array['order_evalbuyer_able']		= '1';
        }
        $order_list		= $model_my_order->myOrderList($array,$page,'order_id,store_id');
        /**
         * 订单下的商品
         */
        if(is_array($order_list) && !empty($order_list)) {
            $order_id_array = array();
            $store_id_array = array();
            $store_array = array();//商城信息
            $refund_array = array();//退款信息
            $return_array = array();//退货信息
            $model_store =new storeModel();
            foreach ($order_list as $v) {
                $order_id_array[] = $v['order_id'];
                if(!in_array($v['store_id'],$store_id_array)) $store_id_array[] = $v['store_id'];
            }
            $order_list		= array();
            $order_list		= $model_my_order->myOrderGoodsList(array('order_id_string'=>"'".implode("','",$order_id_array)."'"));
            $store_list = $model_store->getStoreList(array('store_id_in'=>"'".implode("','",$store_id_array)."'"));//获得订单商城信息
            if (is_array($store_list) && !empty($store_list)){
                foreach ($store_list as $val) {
                    $store_array[$val['store_id']] = $val;
                }
            }
            /**
             * 实例化退款模型
             */
            $model_refund	=new refundModel();
            $condition = array();
            $condition['buyer_id'] = $_SESSION['member_id'];
            $condition['order_ids'] = "'".implode("','",$order_id_array)."'";
            $condition['refund_type'] = '1';
            $refund_list = $model_refund->getList($condition);
            if (is_array($refund_list) && !empty($refund_list)){
                foreach ($refund_list as $val) {
                    $refund_array[$val['order_id']] = $val;
                }
            }
            /**
             * 实例化退货模型
             */
            $model_return	=new returnModel();
            $condition = array();
            $condition['buyer_id'] = $_SESSION['member_id'];
            $condition['order_ids'] = "'".implode("','",$order_id_array)."'";
            $condition['return_type'] = '1';
            $return_list= $model_return->getList($condition);
            if (is_array($return_list) && !empty($return_list)){
                foreach ($return_list as $val) {
                    $return_array[$val['order_id']] = $val;
                }
            }

            $order_array	= array();
            if(is_array($order_list) && !empty($order_list)) {
                $store_id	= 0;
                $store = array();
                foreach ($order_list as $val) {
                    $order_id = $val['order_id'];
                    if(is_array($refund_array[$order_id]) && !empty($refund_array[$order_id])) $val['refund'] = $refund_array[$order_id];
                    if(is_array($return_array[$order_id]) && !empty($return_array[$order_id])) $val['return'] = $return_array[$order_id];
                    $val['spec_info_arr'] = '';
                    if (!empty($val['spec_info'])){
                        $val['spec_info_arr']	= unserialize($val['spec_info']);
                    }
                    $val['state_info']		= orderModel::orderStateInfo($val['order_state'],$val['refund_state']);
                    //$val['state_info']		= $this->orderStateInfo($val['order_state'],$val['refund_state']);
                    $store_id	= $val['store_id'];
                    $store = $store_array[$store_id];
                    /**
                     * 获得联系方式
                     */
                    $val['member_id'] = $store['member_id'];
                    $val['member_name'] = $store['member_name'];
                    $val['store_qq'] = $store['store_qq'];
                    $val['store_ww'] = $store['store_ww'];
                    unset($store);
                    //1.交易成功超过十五天双方都未评价时评价关闭2.一方评价后超过十五天评价结束
                    if ($val['evaluation_status'] == 1){//买家已经评价
                        $val['able_evaluate'] = false;
                    }else {
                        $val['able_evaluate'] = true;
                    }
                    if ($val['able_evaluate'] && $val['evalseller_status'] == 0 && (intval($val['finnshed_time'])+60*60*24*15)<time()){
                        $val['able_evaluate'] = false;
                    }elseif ($val['able_evaluate'] && $val['evalseller_status'] == 1 && (intval($val['evalseller_time'])+60*60*24*15)<time()) {
                        $val['able_evaluate'] = false;
                    }
                    $order_array[$val['order_id']][] = $val;
                }
            }
        }
        Tpl::output('order_array',$order_array);
        $this->_assignMobileData($page);
    }

    protected function getMemberIdIfExists()
    {
        $key = $_POST['key'];
        if (empty($key)) {
            $key = $_GET['key'];
        }

        $model_mb_user_token = Model('mb_user_token');
        $mb_user_token_info = $model_mb_user_token->getMbUserTokenInfoByToken($key);
        if (empty($mb_user_token_info)) {
            return 0;
        }

        return $mb_user_token_info['member_id'];
    }
}


class mobileMemberControl extends MobileControl{

    protected $member_info = array();

    public function __construct() {
        parent::__construct();
        $agent = $_SERVER['HTTP_USER_AGENT'];
        if (strpos($agent, "MicroMessenger") && $_GET["act"]=='auto') {
            $this->appId = C('app_weixin_appid');
            $this->appSecret = C('app_weixin_secret');;
        }else{
            $model_mb_user_token = Model('mb_user_token');
            if(empty($key)) {
                $key = $_GET['key'];
            }if(empty($key)) {
                $key = $_POST['key'];
            }
            if(!empty($key)) {
                $mb_user_token_info = $model_mb_user_token->getMbUserTokenInfoByToken($key);
                if (empty($mb_user_token_info)) {
                    return;
                }
            }

            $model_member = Model('member');
            $this->member_info = $model_member->getMemberInfoByID($_SESSION['member_id']);

            if(empty($this->member_info)) {
                return;
            } else {
                $this->member_info['client_type'] = $mb_user_token_info['client_type'];
                $this->member_info['openid'] = $mb_user_token_info['openid'];
                $this->member_info['token'] = $mb_user_token_info['token'];
                $level_name = $model_member->getOneMemberGrade($_SESSION['member_id']);
                $this->member_info['level_name'] = $level_name['level_name'];
                //读取卖家信息
                $seller_info = Model('seller')->getSellerInfo(array('member_id'=>$this->member_info['member_id']));
                $this->member_info['store_id'] = $seller_info['store_id'];
            }
        }
    }

    public function getOpenId()
    {
        return $this->member_info['openid'];
    }

    public function setOpenId($openId)
    {
        $this->member_info['openid'] = $openId;
        Model('mb_user_token')->updateMemberOpenId($this->member_info['token'], $openId);
    }
}

//产品信息基本控制器
class  mobileCpxxControl extends MobileControl {

    public function __construct(){
        //输出头部的公用信息
        //$this->showLayout();
        //输出会员信息
        //$this->getMemberAndGradeInfo(false);

        Language::read('common,home_layout');

        //Tpl::setDir('home');

        Tpl::setLayout('cpxx_layout');

        if ($_GET['column'] && strtoupper(CHARSET) == 'GBK'){
            $_GET = Language::getGBK($_GET);
        }
        if(!C('site_status')) halt(C('closed_reason'));
        // 自动登录
        //$this->auto_login();
    }
}